var http = require("../../../utils/https.js");

// my/pages/recharge/recharge.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    amountList: ["100元", "200元", "300元", "400元", "500元", "600元"],
    selectedAmount: "100元",
    userInfo: {},
  },
  handleAmountSelect(e) {
    // 先验证事件是否被触发
    //  console.log('点击了：', e.currentTarget.dataset.amount);

    // 确保amount正确获取
    const amount = e.currentTarget.dataset.amount;
    if (!amount) return;

    this.setData({
      selectedAmount: amount
    });
  },
  handleRecharge() {
    // 可在此处编写调用充值接口等逻辑

    var selectMoney = this.data.selectedAmount
    var a = selectMoney.substring(0, selectMoney.length - 1)
    console.log(Number(a));
    var userId = this.data.userInfo.userId
    var that = this
    http.PUT(`/balance/increase?userId=${userId}&balance=${a}`, {}, function (res) {
      if (res.code == 200) {
        wx.showToast({
          title: selectMoney + "充值成功",
          icon: "none",
          duration: 1000
        });
        setTimeout(()=>{
          wx.navigateBack()
        },1000)


      } else {
        that.handleAuthExpired()
      }
      console.log('成功:', res);
    }, function (err) {
      console.error('失败:', err);
    });






  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo: userInfo
    })
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      wx.redirectTo({
        url: '/index/pages/mzhLogin/mzhLogin',
      })
      return
    }
  },
  handleAuthExpired(res) {
    wx.showToast({
      title: '认证过期，请重新登录',
      icon: 'none',
      duration: 1500
    })
    setTimeout(() => {
      wx.redirectTo({
        url: '/index/pages/mzhLogin/mzhLogin',
      })
    }, 1500)
  },
})